﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Deployment;
using Microsoft.Win32;
using System.Security.Permissions;
using System.Globalization;

[assembly: CLSCompliant(true)]
[assembly: SecurityPermission(
   SecurityAction.RequestMinimum, Execution = true)]
namespace PrerequisiteInstaller
{
    public partial class InstallPrerequisite : Form
    {
        public InstallPrerequisite()
        {
            InitializeComponent();
            Application.EnableVisualStyles();
        }

        static string programFilesLocation = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

        private void InstallPrerequisite_Load(object sender, EventArgs e)
        {
            this.pnlInstallingPrerequisite.Visible = true;
            this.pnlInstallationComplete.Visible = false;
            
            lblPrerequisiteMsg.Text = "Checking for prerequisites...";
            UpdateProgramFilesPathFor64BitMachine();
        }

        

        private void InstallPrerequisite_Activated(object sender, EventArgs e)
        {
            this.Refresh();
        }

        private static void UpdateProgramFilesPathFor64BitMachine()
        {
            try
            {
                if (!programFilesLocation.Contains("x86"))
                {
                    if (Directory.Exists(programFilesLocation.TrimEnd() + " (x86)"))
                    {
                        programFilesLocation = programFilesLocation.Replace("Program Files", "Program Files (x86)");
                    }
                }
            }
            catch (Exception)
            {
                //Failed to update program files path
            }
        }

        private void InstallPrerequisite_Shown(object sender, EventArgs e)
        {
            try
            {
                this.BringToFront();
                this.TopLevel = true;
                this.Refresh();

                if (!IsWindowsInstallerInstalled())
                {
                    lblPrerequisiteMsg.Text = "Prerequisite for Ontology Recognition add-in is being installed...";
                    InstallWindowsInstaller();
                }
                else
                {
                    //eventLogger.WriteToLog(LogCategory.Installer, Resource.PRIMINTEROPALREADYINSTALLED);
                    //Log: Primary Interop Assemblies are already installed
                }
                this.pnlInstallingPrerequisite.Visible = false;
                this.pnlInstallationComplete.Visible = true;
                lblBannerHeading.Text = "Installation Complete";
                Font font = new Font("Tahoma", 13);
                lblBannerHeading.Font = font;
                btnFinish.Enabled = true;
                btnFinish.Text = "&Finish";
                btnFinish.Focus();
            }
            catch (Exception)
            {
                //Failed to show Finish Dailog 
            }
        }

        private void InstallWindowsInstaller()
        {
            try
            {
                string osName = GetOSName();
                string installationPath = Path.Combine(programFilesLocation, "Word Add in For Ontology Recognition");
                //MessageBox.Show(osName);
                //MessageBox.Show(installationPath);
                switch (osName)
                {
                    case "Windows Vista":
                        if (Environment.OSVersion.Platform.ToString().Contains("32"))
                        {
                            //Install
                            //x86 Platform: Windows6.0-KB942288-v2-x86.msu (1.7 MB)
                            Process installProcess = new Process();
                            installProcess.StartInfo.FileName = installationPath + @"\Prerequisites\Windows6.0-KB942288-v2-x86.msu";
                            installProcess.Start();
                            while (!installProcess.HasExited)
                            {
                                System.Threading.Thread.Sleep(1000);
                            }
                        }
                        else if (Environment.OSVersion.Platform.ToString().Contains("64"))
                        {
                            //Install
                            //x64 Platform: Windows6.0-KB942288-v2-x64.msu (2.9 MB)
                            Process installProcess = new Process();
                            installProcess.StartInfo.FileName = installationPath + @"\Prerequisites\Windows6.0-KB942288-v2-x64.msu";
                            installProcess.Start();
                            while (!installProcess.HasExited)
                            {
                                System.Threading.Thread.Sleep(1000);
                            }
                        }
                        break;
                    case "Windows XP":
                        {
                            //Install    
                            //x86 Platform: WindowsXP-KB942288-v3-x86.exe (3.2 MB)
                            Process installProcess = new Process();
                            installProcess.StartInfo.FileName = installationPath + @"\Prerequisites\WindowsXP-KB942288-v3-x86.exe";
                            installProcess.Start();
                            while (!installProcess.HasExited)
                            {
                                System.Threading.Thread.Sleep(1000);
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            catch (Exception)
            {
            }
        }

        private bool IsWindowsInstallerInstalled()
        {
            string filepath = Environment.GetFolderPath(Environment.SpecialFolder.System);
            filepath = Path.Combine(filepath, "msiexec.exe");

            if (File.Exists(filepath))
            {
                FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(filepath);
                if (!string.IsNullOrEmpty(fileVersionInfo.FileVersion) &&
                    (fileVersionInfo.ProductVersion.StartsWith("4.5") ||
                    fileVersionInfo.ProductVersion.StartsWith("4.0") ||
                    fileVersionInfo.ProductVersion.StartsWith("3.5") ||
                    fileVersionInfo.ProductVersion.StartsWith("3.1")))
                {
                    return true;
                }
            }
            return false;
        }


        private static string GetOSName()
        {
            OperatingSystem osInfo = Environment.OSVersion;
            string osName = "UNKNOWN";

            try
            {
                switch (osInfo.Platform)
                {
                    case PlatformID.Win32Windows:
                        {
                            switch (osInfo.Version.Minor)
                            {
                                case 0:
                                    {
                                        osName = "Windows 95";
                                        break;
                                    }

                                case 10:
                                    {
                                        if (osInfo.Version.Revision.ToString(CultureInfo.CurrentCulture) == "2222A")
                                        {
                                            osName = "Windows 98 Second Edition";
                                        }
                                        else
                                        {
                                            osName = "Windows 98";
                                        }
                                        break;
                                    }

                                case 90:
                                    {
                                        osName = "Windows Me";
                                        break;
                                    }
                            }
                            break;
                        }

                    case PlatformID.Win32NT:
                        {
                            switch (osInfo.Version.Major)
                            {
                                case 3:
                                    {
                                        osName = "Windows NT 3.51";
                                        break;
                                    }

                                case 4:
                                    {
                                        osName = "Windows NT 4.0";
                                        break;
                                    }

                                case 5:
                                    {
                                        if (osInfo.Version.Minor == 0)
                                        {
                                            osName = "Windows 2000";
                                        }
                                        else if (osInfo.Version.Minor == 1)
                                        {
                                            osName = "Windows XP";
                                        }
                                        else if (osInfo.Version.Minor == 2)
                                        {
                                            osName = "Windows Server 2003";
                                        }
                                        break;
                                    }

                                case 6:
                                case 7:
                                    {
                                        osName = "Windows Vista";
                                        break;
                                    }
                            }
                            break;
                        }
                }
            }
            catch (NullReferenceException ex)
            {
                //Failed to get type of operating system.
            }
            catch (Exception ex)
            {
                //Failed to get type of operating system.
            }
            return osName;
        }

        private void btnFinish_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}
